package com.bst.etl.batch.tasklet;

import com.alibaba.druid.pool.DruidDataSource;
import com.bst.common.exception.base.BaseException;
import com.bst.etl.utils.EtlUtil;
import com.bst.system.framework.datasource.DynamicDataSource;
import com.bst.system.framework.utils.DBUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component("delSQLExecTasklet")
@StepScope
public class DelSQLExecTasklet implements Tasklet {
    @Value("#{jobParameters[idDbTar]}")
    String idDbTar;
    @Value("#{jobParameters[DT_DAY_BEGIN]}")
    Date startDate;
    @Value("#{jobParameters[DT_DAY_END]}")
    Date endDate;
    @Value("#{jobParameters[delSql]}")
    String delSql;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        DruidDataSource dwDataSource = DynamicDataSource.getDataSourceById(idDbTar);
        if (dwDataSource == null) throw new BaseException(String.format("数据源获取失败！"));

        if (StringUtils.isEmpty(this.getSQL())) return RepeatStatus.FINISHED;

        if (StringUtils.isEmpty(this.getSQL()) && this.getSQL().trim().length() <= 6) return RepeatStatus.FINISHED;

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sqls = delSql;
        try {
            connection = dwDataSource.getConnection();
            connection.setAutoCommit(true);
            sqls = EtlUtil.buildSql(this.getSQL(), startDate, endDate, dwDataSource.getDbType());
            List<String> sqlList = new ArrayList<>();
            for (String sql : sqls.split(";")) {
                if (!StringUtils.isEmpty(sql) && sql.trim().length() > 6) {
                    sqlList.add(sql);
                }
            }
            Statement statement = connection.createStatement();

            for (String beforeSql : sqlList) {
                statement.execute(beforeSql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            BaseException baseException = new BaseException("执行SQL错误! SQL语句为:" + sqls);
            throw baseException;
        } finally {
            DBUtil.closeDBResources(null, preparedStatement, connection);
        }

        return RepeatStatus.FINISHED;
    }


    protected String getSQL() {
        return this.delSql;
    }
}